<template>
    <div class="app-container">
      <div class="filter-container">
        <el-form ref="queryForm" size="mini" :model="queryParams" label-position="right" label-width="auto">
          <div class="lineBox">
            <el-form-item label="用户名" prop="name">
              <el-input v-model="queryParams.name" size="mini" placeholder="请输入用户名" clearable style="width: 120px" />
            </el-form-item>
          </div>
          <div class="lineBox">
            <el-form-item label="账号" prop="account">
              <el-input v-model="queryParams.account" size="mini" placeholder="请输入账号" clearable style="width: 120px" />
            </el-form-item>
          </div>
          <div class="lineBox">
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择" clearable size="mini" style="width: 120px">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </div>
          <div class="lineBox">
            <el-button size="mini" type="primary" @click="handleFilter">筛选</el-button>
            <el-button size="mini" @click="resetQuery">重置</el-button>
          </div>
        </el-form>
      </div>
  
      <div class="myTable" style="min-height: 600px">
        <div class="filter-container">
          <div class="operation-buttons">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增用户</el-button>
          </div>
        </div>
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          fit
          size="mini"
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" min-width="60" align="center" />
          <el-table-column prop="name" label="用户名" min-width="100" align="center" show-overflow-tooltip />
          <el-table-column prop="account" label="账号" min-width="120" align="center" show-overflow-tooltip />
          <el-table-column label="角色" min-width="100" align="center">
            <template slot-scope="{row}">
              <span>{{ row.roles }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" min-width="80" align="center">
            <template slot-scope="{row}">
              <el-tag :type="row.status === '1' ? 'success' : 'danger'">
                {{ row.status === '1' ? '正常' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" min-width="160" align="center">
            <template slot-scope="{row}">
              <span>{{ row.create_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="备注" min-width="200" align="center" show-overflow-tooltip />
          <el-table-column fixed="right" label="操作" width="220" align="center" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <el-button type="primary" size="mini" @click="handleEdit(row)">编辑</el-button>
              <el-button :type="row.status === '1' ? 'danger' : 'success'" size="mini" @click="handleToggleStatus(row)">
                {{ row.status === '1' ? '禁用' : '启用' }}
              </el-button>
              <el-button type="danger" size="mini" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <pagination
          size="mini"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.limit"
          layout="total, sizes, prev, pager, next, jumper"
          @pagination="getList"
        />
      </div>
  
      <!-- 新增/编辑用户对话框 -->
      <el-dialog 
        :title="dialogTitle" 
        :visible.sync="dialogVisible" 
        width="500px" 
        class="user-form-dialog"
        :close-on-click-modal="false"
        :before-close="handleDialogClose"
      >
        <el-form ref="userForm" :model="formData.userForm" :rules="formData.userFormRules" label-width="80px">
          <el-form-item label="用户名" prop="name">
            <el-input v-model="formData.userForm.name" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input v-model="formData.userForm.account" placeholder="请输入账号" :disabled="dialogType === 'edit'" />
          </el-form-item>
          
          <template v-if="dialogType === 'add'">
            <el-form-item label="密码" prop="password">
              <el-input v-model="formData.userForm.password" placeholder="请输入密码" show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPwd">
              <el-input v-model="formData.userForm.confirmPwd" placeholder="请再次输入密码" show-password />
            </el-form-item>
          </template>
          
          <template v-else>
            <div v-if="!formData.showEditPassword">
              <el-form-item>
                <el-button type="primary" size="mini" @click="handleShowEditPassword">修改密码</el-button>
              </el-form-item>
            </div>
            <template v-else>
              <el-form-item label="密码" prop="password">
                <el-input v-model="formData.userForm.password" placeholder="请输入新密码" show-password />
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPwd">
                <el-input v-model="formData.userForm.confirmPwd" placeholder="请再次输入密码" show-password />
              </el-form-item>
            </template>
          </template>
          
          <el-form-item label="角色" prop="roles">
            <el-select v-model="formData.userForm.roles" placeholder="请选择角色" style="width: 100%">
              <el-option label="管理员" value="admin" />
              <el-option label="普通用户" value="user" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.userForm.status">
              <el-radio label="1">正常</el-radio>
              <el-radio label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="formData.userForm.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="submitUserForm">确定</el-button>
        </div>
      </el-dialog>
  
      <!-- 单独修改密码对话框 -->
      <el-dialog 
        title="修改密码" 
        :visible.sync="changePasswordDialog.visible" 
        width="400px" 
        :close-on-click-modal="false"
        :before-close="() => changePasswordDialog.visible = false"
      >
        <el-form ref="changePasswordForm" :model="changePasswordDialog.form" :rules="changePasswordDialog.rules" label-width="80px">
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="changePasswordDialog.form.newPassword" placeholder="请输入新密码" show-password />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmNewPassword">
            <el-input v-model="changePasswordDialog.form.confirmNewPassword" placeholder="请确认新密码" show-password />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="changePasswordDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitChangePasswordForm">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { userApi } from '@/api/user'
  import Pagination from '@/components/Pagination'
  import { parseTime } from '@/utils'
  
  export default {
    name: 'UserManagement',
    components: {
      Pagination
    },
    filters: {
      parseTime
    },
    data() {
      return {
        // 表格key
        tableKey: 0,
        // 加载状态
        listLoading: false,
        // 列表数据
        list: [],
        // 总记录数
        total: 0,
        // 查询参数
        queryParams: {
          page: 1,
          limit: 10,
          name: undefined,
          account: undefined,
          status: undefined
        },
        // 状态选项
        statusOptions: [
          { value: '1', label: '正常' },
          { value: '0', label: '禁用' }
        ],
        // 对话框显示状态
        dialogVisible: false,
        // 对话框标题
        dialogTitle: '新增用户',
        // 对话框类型
        dialogType: 'add',
        
        // 表单数据（集中管理所有表单相关数据）
        formData: {
          // 显示修改密码
          showEditPassword: false,
          // 用户表单
          userForm: {
            id: undefined,
            name: '',
            account: '',
            password: '',
            confirmPwd: '',
            status: '1',
            roles: '',
            remarks: ''
          },
          // 校验规则
          userFormRules: {
            name: [
              { required: true, message: '请输入用户名', trigger: 'blur' },
              { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
            ],
            account: [
              { required: true, message: '请输入账号', trigger: 'blur' },
              { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
            ],
            password: [
              { 
                required: true, 
                message: '请输入密码', 
                trigger: 'blur' 
              },
              { 
                min: 6, 
                message: '密码长度不能少于6位', 
                trigger: 'blur' 
              }
            ],
            confirmPwd: [
              { 
                required: true, 
                message: '请再次输入密码', 
                trigger: 'blur' 
              },
              { 
                validator: (rule, value, callback) => {
                  if (value !== this.formData.userForm.password) {
                    callback(new Error('两次输入的密码不一致'))
                  } else {
                    callback()
                  }
                }, 
                trigger: 'blur' 
              }
            ],
            roles: [
              { required: true, message: '请选择角色', trigger: 'change' }
            ],
            status: [
              { required: true, message: '请选择状态', trigger: 'change' }
            ]
          }
        },
        
        // 修改密码对话框
        changePasswordDialog: {
          visible: false,
          userId: null,
          form: {
            newPassword: '',
            confirmNewPassword: ''
          },
          rules: {
            newPassword: [
              { required: true, message: '请输入新密码', trigger: 'blur' },
              { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
            ],
            confirmNewPassword: [
              { required: true, message: '请确认新密码', trigger: 'blur' },
              { 
                validator: (rule, value, callback) => {
                  if (value !== this.changePasswordDialog.form.newPassword) {
                    callback(new Error('两次输入的密码不一致'))
                  } else {
                    callback()
                  }
                }, 
                trigger: 'blur' 
              }
            ]
          }
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      // 获取用户列表
      async getList() {
        this.listLoading = true
        try {
          const response = await userApi('getUserList', this.queryParams)
          if (response.code === 200) {
            this.list = response.data.resultList || []
            this.total = response.data.totalCount || 0
          } else {
            this.$message.error(response.message || '获取用户列表失败')
            this.useTestData()
          }
        } catch (error) {
          console.error('获取用户列表出错:', error)
          this.$message.error('获取用户列表出错')
          this.useTestData()
        } finally {
          setTimeout(() => {
            this.listLoading = false
          }, 500)
        }
      },
      
      // 筛选按钮点击事件
      handleFilter() {
        this.queryParams.page = 1
        this.getList()
      },
      
      // 重置查询条件
      resetQuery() {
        this.queryParams = {
          page: 1,
          limit: 10,
          name: undefined,
          account: undefined,
          status: undefined
        }
        this.getList()
      },
      
      // 关闭对话框
      handleDialogClose() {
        this.dialogVisible = false
        // 重置表单
        this.resetForm()
      },
      
      // 重置表单
      resetForm() {
        // 重置用户表单数据
        this.formData.userForm = {
          id: undefined,
          name: '',
          account: '',
          password: '',
          confirmPwd: '',
          status: '1',
          roles: '',
          remarks: ''
        }
        // 重置修改密码标志
        this.formData.showEditPassword = false
        
        // 清除验证结果
        this.$nextTick(() => {
          if (this.$refs.userForm) {
            this.$refs.userForm.clearValidate()
          }
        })
      },
      
      // 新增用户
      handleAdd() {
        this.dialogType = 'add'
        this.dialogTitle = '新增用户'
        this.resetForm()
        this.dialogVisible = true
      },
      
      // 编辑用户
      handleEdit(row) {
        this.dialogType = 'edit'
        this.dialogTitle = '编辑用户'
        
        // 重置表单
        this.resetForm()
        
        // 设置表单数据
        this.formData.userForm = {
          id: row.id,
          name: row.name,
          account: row.account,
          password: '',
          confirmPwd: '',
          status: row.status,
          roles: row.roles,
          remarks: row.remarks || ''
        }
        
        this.dialogVisible = true
      },
      
      // 显示修改密码表单
      handleShowEditPassword() {
        this.formData.showEditPassword = true
        this.formData.userForm.password = ''
        this.formData.userForm.confirmPwd = ''
        
        this.$nextTick(() => {
          if (this.$refs.userForm) {
            this.$refs.userForm.clearValidate(['password', 'confirmPwd'])
          }
        })
      },
      
      // 切换用户状态
      async handleToggleStatus(row) {
        const statusText = row.status === '1' ? '禁用' : '启用'
        try {
          await this.$confirm(`确认要${statusText}该用户吗?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          
          const newStatus = row.status === '1' ? '0' : '1'
          const response = await userApi('updateUserStatus', { 
            id: row.id, 
            status: newStatus 
          })
          
          if (response.code === 200) {
            this.$message.success(`${statusText}成功`)
            // 更新状态
            row.status = newStatus
          } else {
            this.$message.error(response.message || `${statusText}失败`)
          }
        } catch (error) {
          console.log('操作取消或出错')
        }
      },
      
      // 删除用户
      async handleDelete(row) {
        try {
          await this.$confirm('确认要删除该用户吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          
          const response = await userApi('deleteUser', { id: row.id })
          
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error(response.message || '删除失败')
          }
        } catch (error) {
          console.log('删除操作取消或出错')
        }
      },
      
      // 提交用户表单
      submitUserForm() {
        this.$refs.userForm.validate(async (valid) => {
          if (valid) {
            // 准备提交数据
            const submitData = { ...this.formData.userForm }
            delete submitData.confirmPwd
            
            // 编辑状态，判断是否需要提交密码
            if (this.dialogType === 'edit' && !this.formData.showEditPassword) {
              delete submitData.password
            }
            
            if (this.dialogType === 'edit' && this.formData.showEditPassword && !submitData.password) {
              delete submitData.password
            }
            
            try {
              const apiMethod = this.dialogType === 'add' ? 'addUser' : 'updateUser'
              const response = await userApi(apiMethod, submitData)
              
              if (response.code === 200) {
                this.$message.success(this.dialogType === 'add' ? '新增成功' : '修改成功')
                this.handleDialogClose()
                this.getList()
              } else {
                this.$message.error(response.message || (this.dialogType === 'add' ? '新增失败' : '修改失败'))
              }
            } catch (error) {
              console.error('提交表单出错:', error)
              this.$message.error('操作失败，请稍后重试')
            }
          }
        })
      },
      
      // 打开单独修改密码对话框
      handleChangePassword(userId) {
        this.changePasswordDialog.userId = userId
        this.changePasswordDialog.form = {
          newPassword: '',
          confirmNewPassword: ''
        }
        this.changePasswordDialog.visible = true
        
        this.$nextTick(() => {
          if (this.$refs.changePasswordForm) {
            this.$refs.changePasswordForm.clearValidate()
          }
        })
      },
      
      // 提交修改密码
      submitChangePasswordForm() {
        this.$refs.changePasswordForm.validate(async (valid) => {
          if (valid) {
            try {
              const response = await userApi('updateUserPassword', {
                id: this.changePasswordDialog.userId,
                password: this.changePasswordDialog.form.newPassword
              })
              
              if (response.code === 200) {
                this.$message.success('密码修改成功')
                this.changePasswordDialog.visible = false
              } else {
                this.$message.error(response.message || '密码修改失败')
              }
            } catch (error) {
              console.error('修改密码出错:', error)
              this.$message.error('修改密码失败，请稍后重试')
            }
          }
        })
      },
      
      // 使用测试数据
      useTestData() {
        const now = new Date().toISOString()
        
        this.list = [
          {
            id: 1,
            name: '管理员',
            account: 'admin',
            password: '******',
            roles: 'admin',
            status: '1',
            create_time: now,
            update_time: now,
            remarks: '系统管理员'
          },
          {
            id: 2,
            name: '张三',
            account: 'zhangsan',
            password: '******',
            roles: 'user',
            status: '1',
            create_time: now,
            update_time: now,
            remarks: '普通用户'
          },
          {
            id: 3,
            name: '李四',
            account: 'lisi',
            password: '******',
            roles: 'guest',
            status: '0',
            create_time: now,
            update_time: now,
            remarks: '已禁用的用户'
          }
        ]
        this.total = this.list.length
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .filter-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .operation-buttons {
    display: flex;
    gap: 10px;
    padding-right: 10px;
  }
  
  .lineBox {
    display: inline-block;
    margin-right: 20px;
    margin-bottom: 10px;
  }
  
  ::v-deep .el-checkbox__label {
    font-size: 12px;
  }
  
  ::v-deep .el-form-item__label {
    font-weight: 500;
  }
  
  .user-form-dialog {
    ::v-deep .el-input__inner {
      border-radius: 4px;
    }
    
    ::v-deep .el-dialog__header {
      padding: 15px 20px;
      background-color: #f5f7fa;
      border-bottom: 1px solid #ebeef5;
    }
    
    ::v-deep .el-dialog__title {
      font-size: 16px;
      font-weight: bold;
      color: #303133;
    }
    
    ::v-deep .el-dialog__body {
      padding: 20px 20px 5px 20px;
    }
    
    ::v-deep .el-dialog__footer {
      padding: 15px 20px;
      border-top: 1px solid #ebeef5;
    }
  }
  </style>
  